import React, { useRef, useState } from 'react';
import { Button, Modal, ModalProps } from 'antd';
import type {
  DraggableData,
  DraggableEvent,
  DraggableProps,
} from 'react-draggable';
import Draggable from 'react-draggable';
import classnames from 'classnames';

interface DragProps {
  dragProps?: DraggableProps;
}

interface ModalPropsWithMore extends ModalProps {
  /**
   * 超出后是否在整屏滚动：默认false,在弹窗body中滚动
   */
  screenScroll?: boolean;
}

const App: React.FC<DragProps & ModalPropsWithMore> = ({
  dragProps,
  className,
  screenScroll,
  title,
  children,
  ...resetProps
}) => {
  const [disabled, setDisabled] = useState(true);
  const [bounds, setBounds] = useState({
    left: 0,
    top: 0,
    bottom: 0,
    right: 0,
  });
  const draggleRef = useRef<HTMLDivElement>(null);

  const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
    const { clientWidth, clientHeight } = window.document.documentElement;
    const targetRect = draggleRef.current?.getBoundingClientRect();
    if (!targetRect) {
      return;
    }
    setBounds({
      left: -targetRect.left + uiData.x,
      right: clientWidth - (targetRect.right - uiData.x),
      top: -targetRect.top + uiData.y,
      bottom: clientHeight - (targetRect.bottom - uiData.y),
    });
  };

  return (
    <>
      <Modal
        className={classnames(className, 'modalBox', {
          'ant-modal-body-height': !screenScroll,
        })}
        title={
          <div
            style={{
              width: '100%',
              cursor: 'move',
            }}
            onMouseOver={() => {
              if (disabled) {
                setDisabled(false);
              }
            }}
            onMouseOut={() => {
              setDisabled(true);
            }}
            onFocus={() => {}}
            onBlur={() => {}}
          >
            {title}
          </div>
        }
        modalRender={(modal) => (
          <Draggable
            disabled={disabled}
            bounds={bounds}
            nodeRef={draggleRef}
            onStart={(event, uiData) => onStart(event, uiData)}
            {...dragProps}
          >
            <div ref={draggleRef}>{modal}</div>
          </Draggable>
        )}
        {...resetProps}
      >
        {children}
      </Modal>
    </>
  );
};

export default App;
